package com.thirtydays.frame.util

import android.os.CountDownTimer
import com.blankj.utilcode.util.TimeUtils
import com.thirtydays.frame.ui.text.DownTimeItemTextView
import com.thirtydays.frame.util.ext.formatMMSS

/**
 * @author 小垚
 * @创建时间： 2020/12/17
 * @描述：recycleview  倒计时工具
 **/
object DownTimeUtils {
    /**
     * 开启列表倒计时
     */
    private var map = mutableMapOf<Int, DownTimeItemTextView>()
    fun startDownTime(index: Int, tvTime: DownTimeItemTextView, endTime: String, pattern: String, onFinish: () -> Unit) {
        if (map.containsKey(index)) {
            map[index]?.cancel()
            map.remove(index)
        }
        tvTime.start(endTime, pattern) {
            clearMap()
            onFinish()
        }
        if (!map.containsKey(index)) {
            map[index] = tvTime
        }
    }

    fun clearMap() {
        map.forEach {
            it.value.cancel()
        }
        map.clear()
    }

    /**
     * 开启倒计时
     */
    fun startSingleDownTime(endTime: String, pattern: String, onTick: (Long, String) -> Unit, onFinish: (CountDownTimer) -> Unit): CountDownTimer {
        val endTime = TimeUtils.string2Millis(endTime, pattern)
        val currentTimeMillis = System.currentTimeMillis()
        var millisTotal = endTime - currentTimeMillis

        var downTime = object : CountDownTimer(millisTotal, 1000L) {
            override fun onTick(millisUntilFinished: Long) {
                onTick(millisUntilFinished, millisUntilFinished.formatMMSS())
            }

            override fun onFinish() {
                onFinish(this)
            }
        }
        downTime.start()
        return downTime
    }

    /**
     * 开启倒计时
     */
    fun startSingleDownTime(millisTotal: Long, onTick: (Long, String) -> Unit, onFinish: (CountDownTimer) -> Unit): CountDownTimer {
        var downTime = object : CountDownTimer(millisTotal, 1000L) {
            override fun onTick(millisUntilFinished: Long) {
                onTick(millisUntilFinished, millisUntilFinished.formatMMSS())
            }

            override fun onFinish() {
                onFinish(this)
            }
        }
        downTime.start()
        return downTime
    }

}